import React from 'react';
import { Outlet, useLocation, Link } from 'react-router-dom';
import { RouteConfig } from '../../router/types';
import { SidebarConfig } from '../../router/routeConfig';
import './MainContent.css';

const MainContent: React.FC = () => {
  const location = useLocation();

  // 获取当前页面标题
  const getCurrentTitle = (path: string, routes: RouteConfig[]): string => {
    for (const route of routes) {
      if (route.path === path) return route.title || '首页';
      if (route.items) {
        const childTitle = getCurrentTitle(path, route.items);
        if (childTitle) return childTitle;
      }
    }
    return '404 页面';
  };

  // 生成面包屑
  const getBreadcrumb = (path: string, routes: RouteConfig[]): { path: string; title: string }[] => {
    const breadcrumb: { path: string; title: string }[] = [];
    if (path !== '/') breadcrumb.push({ path: '/', title: '首页' });

    const findRoute = (currentPath: string, currentRoutes: RouteConfig[]) => {
      for (const route of currentRoutes) {
        if (currentPath.startsWith(route.path) && route.title) {
          breadcrumb.push({ path: route.path, title: route.title });
          if (route.items && currentPath !== route.path) {
            findRoute(currentPath, route.items);
          }
          return;
        }
      }
    };

    findRoute(path, routes);
    return breadcrumb;
  };

  const currentTitle = getCurrentTitle(location.pathname, SidebarConfig);
  const breadcrumbList = getBreadcrumb(location.pathname, SidebarConfig);

  return (
      <main className="main-content-container">
        {/* 面包屑 + 标题 */}
        <header className="content-header">
          <div className="breadcrumb">
            {breadcrumbList.map((item, index) => (
                <React.Fragment key={item.path}>
                  <Link to={item.path} className={index === breadcrumbList.length - 1 ? 'active' : ''}>
                    {item.title}
                  </Link>
                  {index < breadcrumbList.length - 1 && <span>/</span>}
                </React.Fragment>
            ))}
          </div>
        </header>
        {/* 内容区域 */}
        <div className="content-body">
          <Outlet /> {/* 渲染当前匹配的路由组件 */}
        </div>
      </main>
  );
};

export default MainContent;
